Skip to content

fix(provider): stabilize Gemma batching memory and decode masks - #364

Closed
anupsv wants to merge 4 commits into
feat/unified-memory-capfrom
fix/gemma-oom-repetition
Closed

anupsv wants to merge 4 commits into
feat/unified-memory-capfrom
fix/gemma-oom-repetition

Conversation

@anupsv

@anupsv anupsv commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Bump mlx-swift-lm to fix: skip batch decode masks when unpadded mlx-swift-lm#40, which returns .none for unpadded single-token batched decode masks while preserving explicit masks for padded rows.
  • Bump provider/coordinator fallback version to 0.6.11 so release/update flow can pick up the runtime fix.
  • Keep the existing provider/coordinator memory-envelope protections in this branch: lower default scheduler concurrency/output cap, propagate OpenAI penalties through the batched path, clamp implicit coordinator max_tokens, and mirror provider cold-load memory accounting in coordinator admission.

Why

Gemma 4 26B QAT was repeating under continuous batching because the batched KV cache forced explicit all-true masks for n == 1 decode, while the regular KVCache path uses no mask. That matches the upstream MLX issue shape and the screenshots. The memory-envelope changes remain useful defense-in-depth for the crash/OOM family.

Tests

  • mlx-swift-lm: swift test --filter ContinuousBatchingTests/testBatchedKVCachesSkipMaskForUnpaddedSingleTokenDecode (failed before fix, passes after)
  • mlx-swift-lm: swift test --filter ContinuousBatchingTests/testBatchedKVCachesKeepMaskForPaddedSingleTokenDecode
  • mlx-swift-lm: swift test --filter ContinuousBatchingTests
  • provider-swift: swift test --filter BatchSchedulerBudgetTests
  • coordinator: go test ./api -run TestLatest|TestImplicit|TestEnsureMaxTokens|TestStreamingReservation|TestBilling
  • coordinator: go test ./registry
  • git diff --check

Notes

This PR is stacked on feat/unified-memory-cap. The submodule code review is in Layr-Labs/mlx-swift-lm#40.


View with Codesmith Autofix with Codesmith
Need help on this PR? Tag /codesmith with what you need. Autofix is disabled.

anupsv added 3 commits June 15, 2026 21:36
… gap)

Closes the follow-up deferred from the cap-rework review: the model-LOAD gate
admits on an ESTIMATE (estimatedMemoryGb = on-disk weight bytes × 1.2), while
the runtime KV budget uses MEASURED live MLX usage. If the estimate under-counts
real residency, a model could load yet have its requests rejected by the KV gate
— a "loaded but unserveable" model the coordinator keeps routing to.

After a model is resident, both load paths now measure the true live KV headroom
under the 90% cap and reject if it's below the minimum serveable KV:

- BatchScheduler gains `measuredLiveKVHeadroomBytes` (liveKVHeadroomBytes from
  real MLX active+cache, with NO 1024-token floor so it reports a true zero) and
  `hasServeableKVHeadroom()` (>= UnifiedMemoryCap.minimumLoadKVBytes, 1 GiB).
- ProviderLoop.ensureModelLoaded and StandaloneServer's lazy-load, right after
  loadModel returns and BEFORE registering the slot, unload + MLX.Memory
  .clearCache() + throw a clear "insufficient KV headroom … — unloaded" error
  (ProviderLoop records it for `doctor`; both mirror evictUntilAvailable so the
  coordinator reroutes). The check runs inside the `isLoadingAny` critical
  section, so the MLX measurement reflects this load with no concurrent race.

This makes the cap invariant hold on MEASURED residency end-to-end, not just the
estimate. Test: postLoadGuardRejectsWhenMeasuredHeadroomBelowMinimum pins the
guard's boundary (an over-estimate-residency model → headroom < min → reject; a
model with real room → admit). 59 tests green across UnifiedMemoryCap +
BatchSchedulerBudget + StandaloneServer suites.
@vercel

vercel Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
d-inference Ready Ready Preview Jun 16, 2026 5:06am
d-inference-console-ui-dev Ready Ready Preview Jun 16, 2026 5:06am
d-inference-landing Ready Ready Preview Jun 16, 2026 5:06am

Request Review

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 4 finding(s) (1 blocking)

  • 🟡 [MEDIUM] coordinator/registry/scheduler.go:863-882 — Complex memory calculation in hot path with multiple floating point operations
    • Suggestion: Pre-calculate constants like providerHardMemoryCapGB and providerEstimatedModelLoadGB outside the admission check, or cache results for repeated calls with same parameters
  • 🔵 [INFO] coordinator/api/consumer.go:1011-1017 — implicitMaxTokensBound called twice with same parameters in handleChatCompletions
    • Suggestion: Store the result of implicitMaxTokensBound(rec.MaxOutputLength) in a variable to avoid duplicate computation
  • 🔵 [INFO] coordinator/api/consumer.go:4106-4108 — implicitMaxTokensBound called twice with same parameters in handleGenericInference
    • Suggestion: Store the result of implicitMaxTokensBound(rec.MaxOutputLength) in a variable to avoid duplicate computation
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1466-1490 — SamplingParams struct created and modified multiple times in makeSamplingParams
    • Suggestion: Initialize SamplingParams with all known values at once instead of creating then modifying with conditional assignments

Type_diligence — 4 finding(s) (2 blocking)

  • 🟡 [MEDIUM] coordinator/api/consumer.go:1008 — map[string]any used for core request parsing without type safety
    • Suggestion: Define a typed struct for request parsing instead of map[string]any to catch field type mismatches at compile time
  • 🟡 [MEDIUM] coordinator/api/consumer.go:1188 — map[string]any used for request modification without type safety
    • Suggestion: Define a typed struct for request parsing instead of map[string]any to catch field type mismatches at compile time
  • 🔵 [INFO] coordinator/api/consumer.go:1048 — explicitMaxTokens function operates on map[string]any without type assertions
    • Suggestion: Add type assertions with ok checks when accessing map values, e.g., if val, ok := parsed["max_tokens"].(int); ok { ... }
  • 🔵 [INFO] coordinator/api/consumer_test.go:1047-1051 — Test uses map[string]any without type safety for test data
    • Suggestion: Use a typed struct for test request data instead of map[string]any to ensure type safety in tests

Additive_complexity — 5 finding(s) (2 blocking)

  • 🔵 [INFO] coordinator/api/consumer.go:1009-1016 — implicitMaxTokensBound function adds unnecessary indirection for simple min operation
    • Suggestion: Inline the logic at call sites: min(defaultMaxOutputTokens, modelMaxOutputLength) when modelMaxOutputLength > 0
  • 🔵 [INFO] coordinator/registry/scheduler.go:135-142 — Five new memory-related constants when existing modelMemoryHeadroomFactor served similar purpose
    • Suggestion: Consider consolidating these constants or documenting why the existing factor pattern wasn't sufficient
  • 🟡 [MEDIUM] coordinator/registry/scheduler.go:165-184 — providerHardMemoryCapGB duplicates memory calculation pattern from existing modelFitsHardware
    • Suggestion: Extract shared memory calculation logic into a common helper function to avoid divergent implementations
  • 🔵 [INFO] provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1466-1490 — makeSamplingParams static method extracts common parameter construction but only used in two places
    • Suggestion: Consider inlining this helper since it's only used twice and the abstraction doesn't hide significant complexity
  • 🔴 [CRITICAL] coordinator/registry/scheduler.go:807-882 — freeMemoryAdmits function grew from simple free memory check to complex multi-path logic with provider-specific constants
    • Suggestion: Split into separate functions for cold-load vs warm-model admission logic, each with clear responsibilities and test coverage

13 finding(s) total, 5 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment thread coordinator/registry/scheduler.go Resolved
Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/api/consumer_test.go Resolved
Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/registry/scheduler.go Resolved
Comment thread coordinator/registry/scheduler.go Resolved
…x/gemma-oom-repetition

# Conflicts:
#	provider-swift/Sources/ProviderCore/Inference/BatchScheduler+Telemetry.swift
#	provider-swift/Sources/ProviderCore/ProviderLoop.swift
#	provider-swift/Sources/ProviderCore/Server/StandaloneServer.swift
#	provider-swift/Tests/ProviderCoreTests/UnifiedMemoryCapTests.swift

@ethenotethan ethenotethan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review — Layr-Labs/d-inference#

Verdict: REQUEST_CHANGES

Security — ✅ No issues found

Performance — 3 finding(s) (3 blocking)

  • 🟡 [MEDIUM] coordinator/registry/scheduler.go:813-881 — freeMemoryAdmits performs redundant calculations of providerEstimatedModelLoadGB and providerHardMemoryCapGB on every call
    • Suggestion: Cache these calculations in the routingSnapshot struct or pre-compute them when the snapshot is created to avoid repeated floating-point arithmetic on hot scheduling paths
  • 🟡 [MEDIUM] coordinator/api/consumer.go:1008-1016 — implicitMaxTokensBound performs the same comparison and calculation repeatedly for identical inputs
    • Suggestion: Add memoization or cache the result since modelMaxOutputLength values are likely to repeat frequently across requests for the same model
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1465-1490 — makeSamplingParams creates new SamplingParams struct on every call with repeated validation logic
    • Suggestion: Consider object pooling for SamplingParams or pre-validate common parameter combinations to reduce allocation overhead in high-throughput scenarios

Type_diligence — 4 finding(s)

  • 🔵 [INFO] coordinator/api/consumer.go:1015 — explicitMaxTokens uses map[string]any for JSON parsing
    • Suggestion: Consider defining a typed struct for request parsing with proper field tags, or use a more specific interface for the expected JSON structure
  • 🔵 [INFO] coordinator/api/consumer.go:1188 — ensureMaxTokensBound uses map[string]any for request modification
    • Suggestion: Consider defining a typed struct for request parsing and modification with proper field tags
  • 🔵 [INFO] coordinator/api/consumer.go:1542 — handleChatCompletions uses map[string]any for JSON parsing
    • Suggestion: Consider defining a typed struct for chat completion requests with proper field tags
  • 🔵 [INFO] coordinator/api/consumer.go:4108 — handleGenericInference uses map[string]any for JSON parsing
    • Suggestion: Consider defining a typed struct for generic inference requests with proper field tags

Additive_complexity — 6 finding(s) (2 blocking)

  • 🔵 [INFO] coordinator/api/consumer.go:1011-1016 — implicitMaxTokensBound function adds unnecessary indirection for simple conditional logic
    • Suggestion: Inline this 6-line function at its call sites or use a simple ternary expression
  • 🔵 [INFO] coordinator/registry/scheduler.go:136-142 — Five new memory-related constants add configuration complexity without clear necessity
    • Suggestion: Consider if these constants could be derived from existing values or if fewer knobs would suffice
  • 🔵 [INFO] coordinator/registry/scheduler.go:165-177 — providerHardMemoryCapGB function wraps simple arithmetic in unnecessary abstraction
    • Suggestion: Inline this calculation or use a simple math.Min call at the usage site
  • 🔵 [INFO] coordinator/registry/scheduler.go:179-184 — providerEstimatedModelLoadGB function is trivial wrapper around multiplication
    • Suggestion: Replace with inline calculation: modelSizeGB * providerModelMemoryOverheadFactor
  • 🟡 [MEDIUM] provider-swift/Sources/ProviderCore/Inference/BatchScheduler.swift:1466-1489 — makeSamplingParams static method extracts common parameter construction but adds cognitive overhead
    • Suggestion: Consider if the duplication removal justifies the added indirection, or inline at call sites
  • 🟡 [MEDIUM] coordinator/registry/scheduler.go:810-882 — freeMemoryAdmits function has grown complex with multiple memory calculation paths and edge cases
    • Suggestion: Split into separate functions for cold-load vs warm-model admission logic to improve readability

13 finding(s) total, 5 blocking. Verdict: REQUEST_CHANGES.

🤖 Automated review by Centaur · DAR-186

Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/api/consumer.go Resolved
Comment thread coordinator/registry/scheduler.go Resolved
Comment thread coordinator/registry/scheduler.go Resolved
Comment thread coordinator/registry/scheduler.go Resolved
@anupsv

anupsv commented Jun 16, 2026

Copy link
Copy Markdown
Contributor Author

Superseded — split into focused PRs. This branch bundled three unrelated concerns; here's where each went:

  1. Gemma-4 repetition fix (decode-mask divergence — mlx-swift-lm bump + 0.6.11 version) → merged to master via fix(provider): Gemma 4 VLM continuous-batched decode — no more repetition #369 (released in v0.6.11). fix(provider): Gemma 4 VLM continuous-batched decode — no more repetition #369's mlx-swift-lm fix ("only skip decode mask when retained KV fits the window") is a strictly more correct version of what this branch carried, so nothing to port.

  2. Post-load measured-headroom guard → duplicate of the commit already on feat/unified-memory-cap (Enforce a 90% unified-memory cap + purge KV on unload #363); no separate change needed.

  3. Gemma batching memory envelope (the [metal::malloc] Resource limit (499000) crash defense-in-depth: concurrency 24→4, default max_tokens 4096→1024, no auto-raise of omitted max_tokens, coordinator cold-load admission mirroring the provider's real MLX ceiling, OpenAI penalty propagation) → extracted into fix(provider): bound the Gemma batching memory envelope #379 against master, with two review findings fixed (coordinator cap now aligned to master's physical − 6 GB provider ceiling; both cold-load paths share one min-KV floor). Dual-review passed; full coordinator suite green.

No code from this branch is lost — the keep-worthy half is #379, the rest is already on master.

jonathan308 added a commit that referenced this pull request Nov 8, 2026
The rebased SDK #364 keeps main's operation-count Gemma4DecodeCommandBuffers
(mlx-swift-lm #376, adopted here by #1712) instead of its earlier scoped
100-operation/512 M-element limit, so this pin adds only the dense GeGLU
product. Say so in the inference and hardware notes and the changelog
fragment, and note that the endpoint screen measured both changes together.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Nov 8, 2026
Layr-Labs/mlx-swift-lm#364 was rebased onto main 67110e7b (dev's pin), so
this moves the gitlink from dev's 67110e7b to its new head. The rebased
SDK change is the dense GeGLU product (plus its tests, benchmark record and
DocC reference fixes); its decode command-buffer limits resolved to main's
#376 policy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Nov 8, 2026
Layr-Labs/mlx-swift-lm#365 (compiled Gemma feed-forward graphs) was rebased
onto the rebased #364, so this moves the gitlink to its new head.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Nov 8, 2026
Layr-Labs/mlx-swift-lm#364 was rebased onto main 67110e7b (dev's pin), so
this moves the gitlink from dev's 67110e7b to its new head. The rebased
SDK change is the dense GeGLU product (plus its tests, benchmark record and
DocC reference fixes); its decode command-buffer limits resolved to main's
#376 policy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Nov 8, 2026
Layr-Labs/mlx-swift-lm#365 (compiled Gemma feed-forward graphs) was rebased
onto the rebased #364, so this moves the gitlink to its new head.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Nov 10, 2026
The library pull request branch now holds a merge of library main
7f196e02c2, so the pin moves from 6d2c82a0e4 to that merge. The merge adds
library #395 (nullable tool arguments), #302 (the Qwen3.5 MTP prefill
projects only the last prompt position), #364 (the Gemma 4 dispatch change),
#365 (reuse of compiled Gemma 4 feed-forward graphs) and #366 (greedy
batches skip unused sampler metadata). dev does not have them yet. No
provider source changes.

The pin stays provisional until the library pull request merges.

Co-Authored-By: Claude <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Nov 10, 2026
libs/mlx-swift-lm moves from fd48d47f to 093563be, the merge commit of mlx-swift-lm #367 on
main. It holds every 0.10.12 SDK PR, each merged with a merge commit: #372, #301, #395 (nullable
tool arguments), #302, #364, #365, #366 and #367. libs/mlx-swift and libs/mlx are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Nov 10, 2026
libs/mlx-swift-lm moves from 04940f55 to 093563be, the merge commit of mlx-swift-lm #367 on
main. It holds every 0.10.12 SDK PR, each merged with a merge commit: #372, #301, #395 (nullable
tool arguments), #302, #364, #365, #366 and #367. libs/mlx-swift and libs/mlx are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Nov 10, 2026
libs/mlx-swift-lm moves from 1aace467 to 093563be, the merge commit of mlx-swift-lm #367 on
main. It holds every 0.10.12 SDK PR, each merged with a merge commit: #372, #301, #395 (nullable
tool arguments), #302, #364, #365, #366 and #367. libs/mlx-swift and libs/mlx are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Nov 10, 2026
libs/mlx-swift-lm moves from f6b9ac22 to 093563be, the merge commit of mlx-swift-lm #367 on
main. It holds every 0.10.12 SDK PR, each merged with a merge commit: #372, #301, #395 (nullable
tool arguments), #302, #364, #365, #366 and #367. libs/mlx-swift and libs/mlx are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
jonathan308 added a commit that referenced this pull request Nov 10, 2026
libs/mlx-swift-lm moves from 51da1368 to 093563be, the merge commit of mlx-swift-lm #367 on
main. It holds every 0.10.12 SDK PR, each merged with a merge commit: #372, #301, #395 (nullable
tool arguments), #302, #364, #365, #366 and #367. libs/mlx-swift and libs/mlx are unchanged.

changelog.d/qwen35-mtp-prefill-last-row.md: mlx-swift-lm #302 (Qwen 3.5 MTP prompts project only their last
position) rides this pin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch had an error being deployed

1 failed and 3 active deployments
Preview – d-inference — 5f1c3340 Deployed Jun 16, 2026 by vercel[bot]
Preview – d-inference-console-ui-dev — 5f1c3340 Deployed Jun 16, 2026 by vercel[bot]
Preview – d-inference-landing — 5f1c3340 Deployed Jun 16, 2026 by vercel[bot]
benchmarks — 5f1c3340 Deployed Jun 16, 2026 by anupsv via E2E Benchmarks #1001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants